package com.njg.juc.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket {
    private int ticket = 50;

    /*public synchronized void saleTicket() {
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + "\t" + "卖出第：" + (ticket--) + "\t 还剩下：" + ticket);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }*/

    private final Lock lock = new ReentrantLock(); // ReentrantLock 叫可重入锁+默认悲观锁+默认非公平锁
    public void saleTicket(){
        lock.lock();
        try {
            if(ticket > 0){
                System.out.println(Thread.currentThread().getName() + "\t" + "卖出第：" + (ticket--) + "\t 还剩下：" + ticket);
            }
        } finally {

            lock.unlock();
        }
    }

}


/**
 * juc小口诀第一式：
 * <p>
 * 在高内聚低耦合的前提下 ：  线程    操作    资源类
 */
public class SaleTicketDemo {
    public static void main(String[] args) {

        //Thread(Runnable target, String name) Allocates a new Thread object.

        Ticket ticket = new Ticket();

        /*new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    ticket.saleTicket();
                }
            }
        },"A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    ticket.saleTicket();
                }
            }
        },"B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    ticket.saleTicket();
                }
            }
        },"C").start();*/

        new Thread(() -> { for (int i = 0; i < 50; i++) ticket.saleTicket(); }, "A").start();
        new Thread(() -> { for (int i = 0; i < 50; i++) ticket.saleTicket(); }, "B").start();
        new Thread(() -> { for (int i = 0; i < 50; i++) ticket.saleTicket(); }, "C").start();

    }
}
